import { isEmpty } from "../../utils/util";
import { userLogin } from "../../services/login/login";

Page({
  data: {
    image: '../../../assets/fei_logo.png',
    msg_visible: false,
    msg_text: '学号未找到或密码错误！',
    login_form: {
      usernameInputValue: '',
      passwordInputValue: ''
    }
  },

  onUsernameBlur(e) {
    this.setData({
      login_form: {
        usernameInputValue: e.detail.value,
        passwordInputValue: this.data.login_form.passwordInputValue
      }
    });
  },

  onPasswordBlur(e) {
    this.setData({
      login_form:{
        usernameInputValue: this.data.login_form.usernameInputValue,
        passwordInputValue: e.detail.value
      }
    });
  },

  onLoad() {
    wx.getStorage({
      key: 'access_token',
      success (res) {
        if (!!res.data) {
          // wx.switchTab({
          //   url: `/pages/home/home`,
          // });
          console.log(res.data, "access_token");
        }
      }
    })
  },
  
  onLoginButtonClickHandle(e) {
    const username = this.data.login_form.usernameInputValue;
    const password = this.data.login_form.passwordInputValue;

    if(isEmpty(username) || isEmpty(password)) {
      this.setData({
        msg_visible: true,
        msg_text: '学号或密码没有填写！'
      });
    } else {
        this.setData({
          msg_visible: false,
        });

        let query_data = {
          username,
          password
        };

        userLogin(query_data).then((data) => {
          const {access_token, user_id} = data;
          wx.setStorage({
            key: "access_token",
            data: access_token,
            success: function() {      //缓存成功后，输出提示
              console.log('写入access_token缓存成功')
              wx.setStorageSync('user_id', user_id);

              wx.navigateTo({
                url: '/pages/login/wxlogin/index',
              });
            },
            fail: function() {        //缓存失败后的提示
              console.log('写入access_token时发生错误')
            }
          });
        });
    }
  },

});